import json

from django.core import serializers
from django.core.files.storage import FileSystemStorage
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.views import View

from .config import Config
from .models import BookInfo


# Create your views here.
def index(request):
    # return HttpResponse("Hello, world. You're at the index page.")
    context = {'title': 'Django Book Manager'}
    return render(request, 'book_manager/index.html', context)


def http_url_data(request, id, title):
    print(f'id: {id}, title: {title}')
    return JsonResponse({'id': id, 'title': title})


def http_get_data(request):
    query_dict_get = request.GET
    name = query_dict_get.get('name')
    keys = query_dict_get.getlist('keys')
    print(f'name: {name}, keys: {keys}')
    return JsonResponse({'name': name, 'keys': keys})


def http_post_form_data(request):
    form_post = request.POST
    name = form_post.get('name')
    keys = form_post.getlist('keys')
    return JsonResponse({'name': name, 'keys': keys})


def http_post_json_data(request):
    json_str = request.body
    # json_str = json_str.decode('utf-8')
    data = json.loads(json_str)
    name = data.get('name')
    keys = data.get('keys')
    return JsonResponse({'name': name, 'keys': keys})
    # return HttpResponse(normal_string)


def mobile_convert(request, phone):
    print(phone)
    return HttpResponse(phone)


# https://www.runoob.com/http/http-status-codes.html
def http_response_test(request):
    resp = HttpResponse('sahgdasda响应内容', status=200)

    # 响应头设置处理
    resp['name'] = 'cloud9'
    return resp


def json_response_test(request):
    result = {'aaa': 'hello world', 'vv': ['hello world', 'hello world2']}
    # 是否使用安全JSON序列化，默认是，不符合字典类型将抛出异常
    return JsonResponse(data=result, safe=False)


# 重定向到外部页面
def http_redirect(request):
    return redirect('https://www.bilibili.com/video/BV1nf4y1k7G3?p=72')


# 重定向到admin页面
def admin_redirect(request):
    return redirect('/admin')


def get_all_cookie(request):
    cookies = request.COOKIES
    return JsonResponse(cookies)


def set_cookie(request):
    resp = HttpResponse('set_cookie')
    resp.set_cookie('sss', 3435)
    # 设置存活时限
    resp.set_cookie('name', 'cloud9-234', max_age=60 * 60)
    return resp


def get_cookie(request):
    get_para = request.GET
    cookies = request.COOKIES
    name_key = get_para.get('name')
    name = cookies.get(name_key)
    return HttpResponse(name)


def del_cookie(request):
    get_para = request.GET
    cookie_name = get_para.get('name')
    resp = HttpResponse('ok')
    resp.delete_cookie(cookie_name)
    return resp


def get_all_session(request):
    session = request.session
    ss_map = {}
    for key in session.keys():
        ss_map[key] = session[key]
    return JsonResponse(ss_map)


def clear_session(request):
    request.session.clear()
    return JsonResponse('clear ok')


def flush_session(request):
    request.session.clear()
    return JsonResponse('clear ok')


# 5）删除session中的指定键及值，在存储中只删除某个键及对应的值。
def del_session(request):
    get_para = request.GET
    key_name = get_para.get('name')
    del request.session[key_name]
    return JsonResponse('delete ok')


def set_session(request):
    get_para = request.GET
    for key in get_para.keys():
        request.session[key] = get_para[key]
    return HttpResponse('set ok')


# 6）设置session的有效期
# 如果value是一个整数，session将在value秒没有活动后过期。
# 如果value为0，那么用户session的Cookie将在用户的浏览器关闭时过期。
# 如果value为None，那么session有效期将采用系统默认值， 默认为两周，可以通过在settings.py中设置SESSION_COOKIE_AGE来设置全局默认值。
def set_session_expiry(request):
    get_para = request.GET
    key_name = get_para.get('expiry')
    request.session.set_expiry(key_name)
    return HttpResponse('expire set ok')


def custom_config(request):
    config = Config()
    print(config.MY_CUSTOM_SETTING)
    return HttpResponse('custom_config get ok')


def get_book_info_list(request):
    all_books = BookInfo.objects.all()
    data = serializers.serialize('json', all_books)
    return HttpResponse(data, content_type='application/json')


def add_book_info(request):
    all_books = BookInfo.objects.all()
    data = serializers.serialize('json', all_books)
    return HttpResponse(data, content_type='application/json')


def upload_file(request):
    if request.method == 'POST' and 'file' in request.FILES:
        myfile = request.FILES['file']
        fs = FileSystemStorage()
        filename = fs.save(myfile.name, myfile)
        uploaded_file_url = fs.url(filename)
        return HttpResponse(f"File {myfile.name} uploaded successfully. URL: {uploaded_file_url}")
    else:
        return HttpResponse("Invalid request, expecting POST with file field.")


# 类视图的使用
class BookInfoView(View):
    def get(self, request):
        return HttpResponse('get method active!')

    def post(self, request):
        return HttpResponse('post method active!')

    def delete(self, request):
        return HttpResponse('delete method active!')

    def put(self, request):
        return HttpResponse('put method active!')

    def patch(self, request):
        return HttpResponse('patch method active!')